/**
 *       Copyright (c) 2012 Lukas Zaruba
 *
 *   This file is part of Robot Playground.
 *
 *   Robot Playground is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   Robot Playground is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with Robot Playground. If not, see <http://www.gnu.org/licenses/>.
 */
package net.zarubsys.robotplayground.gui.dummydevice.modules;

import java.io.File;

import net.zarubsys.robotplayground.core.modules.IModuleConfiguration;
import net.zarubsys.robotplayground.core.session.ModuleSessionContainer;
import net.zarubsys.robotplayground.core.session.Session;
import net.zarubsys.robotplayground.dummydevice.modules.obstacles.DummyObstaclesModule;
import net.zarubsys.robotplayground.dummydevice.modules.obstacles.DummyObstaclesModuleConfiguration;
import net.zarubsys.robotplayground.gui.dummydevice.plugin.DummyDeviceGUIPlugin;
import net.zarubsys.robotplayground.gui.session.providers.IOpenable;
import net.zarubsys.robotplayground.gui.session.providers.ISystemObjectChangeListener;
import net.zarubsys.robotplayground.gui.session.providers.ISystemObjectChangeNotifier;
import net.zarubsys.robotplayground.gui.session.providers.ISystemObjectGUIProvider;
import net.zarubsys.robotplayground.gui.session.providers.SystemObjectGUIProviderClass;

import org.apache.log4j.Logger;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

/**
 * DummyObstaclesModuleGUIProvider
 *
 * @author Lukas Zaruba, lukas.zaruba@gmail.com
 */
public class DummyObstaclesModuleGUIProvider implements ISystemObjectGUIProvider, IOpenable, ISystemObjectChangeNotifier {
	
	private static final Logger LOG = Logger.getLogger(DummyObstaclesModuleGUIProvider.class);

	@Override
	public Image getImage(String id) {
		return DummyDeviceGUIPlugin.getDefault().getImage(DummyDeviceGUIPlugin.DUMMY_OBSTACLES);
	}

	@Override
	public String getDescription(String id) {
		return "Dummy Obstacles";
	}

	@Override
	public String getDescription(Session session, int index) {
		return getDescription(session.getModules().get(index).getModuleId());
	}

	@Override
	public SystemObjectGUIProviderClass getProviderClass() {
		return SystemObjectGUIProviderClass.MODULE;
	}

	@Override
	public int addObjectToSession(Session session, String id) {
		DummyObstaclesWizard wizard = new DummyObstaclesWizard();
	    WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), wizard);
	    dialog.create();
	    if (dialog.open() != Window.OK) return -1;
	    File file = wizard.getResultFile().getRawLocation().toFile();
	    DummyObstaclesModuleConfiguration configuration = new DummyObstaclesModuleConfiguration(file);
		session.getModules().add(new ModuleSessionContainer(DummyObstaclesModule.ID, configuration));
		return session.getModules().size() - 1;
	}

	@Override
	public boolean reconfigure(Session session, int index) {
		return false;
	}

	@Override
	public boolean isConfigurable(String id) {
		return false;
	}

	@Override
	public boolean remove(Session session, int index) {
		session.getModules().remove(index);
		return true;
	}

	@Override
	public String validate(Session session, int index) {
		IModuleConfiguration configuration = session.getModules().get(index).getConfiguration();
		if (!(configuration instanceof DummyObstaclesModuleConfiguration)) {
			throw new IllegalArgumentException("Unexpected type of configuration " + configuration);
		}
		DummyObstaclesModuleConfiguration obstConf = (DummyObstaclesModuleConfiguration) configuration;
		try {
			DummyObstaclesModuleConfiguration.loadMapFromFile(obstConf.getFile());
			return null;
		} catch (Exception e) {
			return e.getMessage();
		}
	}

	@Override
	public void openResource(Session session, int index) {
		IModuleConfiguration cfg = session.getModules().get(index).getConfiguration();
		if (!(cfg instanceof DummyObstaclesModuleConfiguration)) return;
		DummyObstaclesModuleConfiguration obstaclesCfg = (DummyObstaclesModuleConfiguration) cfg;  
		IFile iFile = getWorkspaceResource(obstaclesCfg);
		try {
			IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), iFile);
		} catch (PartInitException e) {
			LOG.error("Error while openning editor for resource " + iFile + "!", e);
			throw new RuntimeException(e);
		}
	}
	
	private static IFile getWorkspaceResource(DummyObstaclesModuleConfiguration obstaclesCfg) {
		File file = obstaclesCfg.getFile();
		IFile iFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new Path(file.toString()));
		if (iFile == null) {
			throw new IllegalStateException("Cannot get the workspace resource for external path " + file + "!");
		}
		return iFile;
	}

	@Override
	public boolean registerListener(final ISystemObjectChangeListener listener, Session session, int index) {
		IModuleConfiguration cfg = session.getModules().get(index).getConfiguration();
		if (!(cfg instanceof DummyObstaclesModuleConfiguration)) return false;
		DummyObstaclesModuleConfiguration obstaclesCfg = (DummyObstaclesModuleConfiguration) cfg;
		final IFile iFile = getWorkspaceResource(obstaclesCfg);
		ResourcesPlugin.getWorkspace().addResourceChangeListener(new IResourceChangeListener() {
			
			@Override
			public void resourceChanged(IResourceChangeEvent event) {
				if (event.getDelta().findMember(iFile.getFullPath()) == null) return;
				listener.notifyChanged();
			}
			
		}, IResourceChangeEvent.POST_CHANGE);
		return true;
	}

}

